package com.c2.web.backend;
import com.c2.entity.EbNews;
import com.c2.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    /**
     * 将数据放到 model中，将页面放到view中
     * spring mvc---将model渲染到view中
     *
     * list ---分页请求数据
     */
    @RequestMapping("/list")
    public String list(Model model,@RequestParam(value="page",defaultValue = "1") int page,@RequestParam(value = "pageSize",defaultValue = "5") int pageSize){
        System.out.println("start service....."+page);
        //1.请求service层获取新闻的分页数据
        List<EbNews> newsList = newsService.listByPage(page,pageSize);
        /*调用service获取总页数*/
         int totalPage=newsService.getMaxPage(pageSize);
        //2.传递model(数据)和view视图(jsp)
        model.addAttribute("newsList",newsList);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("curPage",page);
        return "manage/news";//视图  通过manage/news.jsp进行展示数据
    }

    @RequestMapping("/to save")
    public  String toSave(){
        return "manage/news-add";
    }

    @RequestMapping("/save_commit")
    public String saveCommit(EbNews ebNews){
        System.out.println("...."+ebNews);
      /* if(ebNews.getEnTitle()==null||ebNews.getEnTitle().trim().length()==0){
            return "manage/paramError";
            //throw new EbExection();
        }*/
    //  Date date=new Date();
        Integer result=newsService.save(ebNews);
        if(result<1) {
            return "manage/manage-error-news";
        }
        return "manage/manage-result-news";
    }

    @RequestMapping("delete/{id}")
    public String delete( @PathVariable("id") Integer id){
        int result=newsService.deleteById(id);
        if(result==0){
              return null;
        }
        return "manage/manage-result-news";
    }

    @RequestMapping("/edit")
    public String edit(Model model,Integer enId){
        System.out.println("enId="+enId);
        EbNews ebNews=newsService.selectById(enId);
        model.addAttribute("ebNews",ebNews);
               return "manage/news-modify";
    }

    @RequestMapping("/editSubmit")
    public String editSubmit(EbNews ebNews){
        System.out.println(ebNews);
        int result=newsService.updateById(ebNews);
        if(result<=0){
            return "manage/manage-error-news";
        }
        return "manage/manage-result-news";
    }

}
